package com.qf.openapi.web.master.controller;

import com.qf.openapi.web.master.entity.User;
import com.qf.openapi.web.master.service.UserService;
import com.qf.openapi.web.master.utils.Constants;
import com.qf.openapi.web.master.utils.QfFileAppender;
import com.qf.openapi.web.master.vo.ResultVo;
import com.qf.openapi.web.master.vo.TableVo;
import com.qf.openapi.web.master.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/user")
@Slf4j//可以使用log对象进行日志的打印
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public ResultVo login(String username, String password, String captcha, Boolean autoLogin, HttpSession session, HttpServletResponse response) {
        log.debug("username={},password={},captcha={},autoLogin={}", username, password, captcha, autoLogin);
        //处理验证码是否正确
        String cap = (String) session.getAttribute("captcha");
        if (!captcha.equalsIgnoreCase(cap)) {
            return new ResultVo(Constants.FAIL_CODE, "验证码错误");
        }
        //调用service层方法进行登陆验证
        User user = userService.login(username, password);
        log.info("调用service层方法校验用户密码，返回的user对象={}", user);
        //如果user不为null则登陆成功，否则失败
        ResultVo resultVo = null;
        if (user != null) {
            resultVo = new ResultVo(Constants.SUCCESS_CODE, "登陆成功");
            session.setAttribute(Constants.SESSION_USER_KEY, user);
            if (autoLogin != null && autoLogin) {
                Cookie usernameNookie = new Cookie("username", user.getName());
                Cookie passwordCookie = new Cookie("password", user.getPassword());
                usernameNookie.setMaxAge(3600);
                passwordCookie.setMaxAge(3600);
                usernameNookie.setPath("/");
                passwordCookie.setPath("/");
                response.addCookie(usernameNookie);
                response.addCookie(passwordCookie);
            }
        } else {
            resultVo = new ResultVo(Constants.FAIL_CODE, "登陆失败");
        }
        return resultVo;
    }

    @PostMapping("/register")
    public ResultVo register(UserVo userVo, HttpSession session) throws ParseException, IOException {
        log.debug("username={},password={},sex={},birthday={},captcha={}", userVo.getUsername(), userVo.getPassword(), userVo.getSex(), userVo.getBirthday(), userVo.getCaptcha());
        ResultVo checkResult = checkUsername(userVo.getUsername());
        if (checkResult.getCode() == -1) {
            return checkResult;
        }
        //处理验证码是否正确
        String cap = (String) session.getAttribute("captcha");
        if (!userVo.getCaptcha().equalsIgnoreCase(cap)) {
            return new ResultVo(Constants.FAIL_CODE, "验证码错误");
        }
        ServletContext context = session.getServletContext();
        String realPath = context.getRealPath(Constants.UPLOAD_PATH);
        return userService.register(userVo, realPath);
    }

    @PostMapping("/checkUsername")
    public ResultVo checkUsername(String username) {
        //查询用户名是否存在
        boolean flag = userService.checkUsername(username);
        ResultVo resultVo = null;
        if (flag) {
            resultVo = new ResultVo(Constants.FAIL_CODE, "此用户名已存在");
        } else {
            resultVo = new ResultVo(Constants.SUCCESS_CODE, "此用户名可以使用");
        }
        return resultVo;
    }

    @GetMapping("/currentUser")
    public ResultVo currentUser(HttpSession session) {
        // 从session中获取用户信息 ，放入ResultVO返回
        User user = (User) session.getAttribute(Constants.SESSION_USER_KEY);
        if (user != null) {
            return new ResultVo(Constants.SUCCESS_CODE, "获取用户信息成功", user.getName());
        } else {
            return new ResultVo(Constants.FAIL_CODE, "获取用户信息失败");
        }
    }

    @GetMapping("/pic")
    public void getUserPic(HttpSession session, HttpServletResponse response) {
        User user = (User) session.getAttribute(Constants.SESSION_USER_KEY);
        if (user != null) {
            String photopath = user.getPhotopath();
            ServletContext context = session.getServletContext();
            String realPath = context.getRealPath(Constants.UPLOAD_PATH);
            String finalFilePath = realPath + File.separator + photopath;
            try {
                IOUtils.copy(new FileInputStream(finalFilePath), response.getOutputStream());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        } else {
            return;
        }
    }

    /**
     * 用户数据表格分页查询接口
     *
     * @param page  页号
     * @param limit 页大小
     * @return
     */
    @GetMapping("/getAllUsers")
    public TableVo<User> getAllUsers(Integer page, Integer limit) {
        return userService.getAllUsersByPage(page, limit);
    }

    @PostMapping("/delUser")
    public ResultVo delUser(Integer[] ids) {
        return userService.delUserByIds(ids);
    }

    @PostMapping("/add")
    public ResultVo addUser(User user) {
        user.setRegistTime(new Date());
        user.setAuth("normal");
        return userService.addUser(user);
    }

    @PostMapping("/update")
    public ResultVo updateUser(User user) {
        return userService.updateUser(user);
    }

    @GetMapping("/selectUser")
    public TableVo<User> selectUser(Integer page, Integer limit, UserVo userVo) {
        TableVo<User> tableVo = userService.getUsersByContdition(page, limit, userVo);
        return tableVo;
    }

    @GetMapping("/export")
    public ResultVo export(HttpServletRequest request) {
        String filename = UUID.randomUUID() + ".csv";
        List<User> users = userService.findAllUsers();
        List<String> usersList = users.stream().map(user -> user.toCSVString()).collect(Collectors.toList());
        ServletContext servletContext = request.getServletContext();
        String realPath = servletContext.getRealPath(Constants.UPLOAD_PATH);
        String finalFilepath = realPath + File.separator + filename;
        File file = new File(finalFilepath);
        QfFileAppender qfFileAppender = null;
        try {
            qfFileAppender = new QfFileAppender(finalFilepath);
            if (!file.exists()) {
                file.createNewFile();
            }
            qfFileAppender.appendListToFile(usersList);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                qfFileAppender.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return new ResultVo(1, "文件创建成功", filename);
    }

    @RequestMapping("/upload")
    public ResultVo upload(MultipartFile file) {
        return userService.addUserByFile(file);
    }
}
